<?php
#=========================================================================================
#	Filename: parseCountryCode.class.php
#	Note	: parseCountryCode Class For parse xml
#	Version : 1.0
#	Author  : Peter Zhang <peter.zhang@achievo.com>
#	Update  : 2010-05-11
#======================================================================================== 


class ParseCountryCode{
	
	/*
	 * e.g array('Africa'=> array('Africa'=> array('AO'=>'Angola','BF'=>' Burkina Faso')));
	 * 
	 */
	public static function parseXml($configFile,$exceptFlag=FALSE,$region='all'){
		
		$retrun = array();
		if(file_exists($configFile)){
			
			//$configArray = ConfigReaderFactory::getInstance()->getConfigReader($configFile)->getConfig();
			$configArray = simplexml_load_file($configFile);
			//return $configArray;
			foreach($configArray->region as $regionKey => $regionValue){
                $regionVar = (string)$regionValue->attributes()->name;
                $countryArray = array();
                if('all' == $region)
                {
                    //change to string
                    foreach ($regionValue->country as $ccKey => $ccValue){

                        //change to string
                        $code = (string)$ccValue->attributes()->code;
                        $name = (string)$ccValue->attributes()->name;
                        $countryFlag = (string)$ccValue->attributes()->except;
                        if($exceptFlag)
                            $countryArray[$code] = array($name,$countryFlag);
                        else 
                            $countryArray[$code] = $name;
                    }
                    uasort($countryArray, 'tmp_usort_country');
                    //two region keys
                    $return[$regionVar][$regionVar]  = $countryArray;
                }
                if($region  == $regionVar )
                {
                    //change to string
                    foreach ($regionValue->country as $ccKey => $ccValue){

                        //change to string
                        $code = (string)$ccValue->attributes()->code;
                        $name = (string)$ccValue->attributes()->name;
                        $countryFlag = (string)$ccValue->attributes()->except;
                        if($exceptFlag)
                            $countryArray[$code] = array($name,$countryFlag);
                        else 
                            $countryArray[$code] = $name;
                    }
                    uasort($countryArray, 'tmp_usort_country');
                    //two region keys
                    $return[$regionVar]  = $countryArray;
                
                }
			}
			return $return;
			
		}else{
			//Error: file not exists,or file path is wrong
			return false;	
		}
	}

	/**
	 * Change country_allow/deny_list format from "HK,MO" to {"Asia":{"Asia":{"HK":"Hong Kong ","MO":"Macau "}}}
	 * 
	 * @author vanni.fan@achievo.com
	 * @param string $config 
	 * @param string $str 
	 * @param boolean $deny 
	 * @return string json
	 */
	public static function country2json($config,$str,$deny){
		static $countries;
		if(is_null($countries)){
			$rs = self::parseXml($config, true);
			foreach($rs as $region_name => $zones){
				foreach($zones as $zone_name => $_countries){
					foreach($_countries as $country_name => $country){
						$countries[$country_name] = array(
							'region' => $region_name,
							'zone' => $zone_name,
							'name' => $country[0],
							'deny' => ($country[1] && $country[1]=='true')
						);
					}
				}
			}
		}
		if(strtoupper(substr($str,0,3))=='ALL' || !trim($str)) return strtoupper(trim($str));

		#print_r($countries);
		$my_countries = explode(',',$str);
		$new_country  = array();
		foreach($my_countries as $code){
			if(isset($countries[$code])){
				$data = $countries[$code];
			//	if(!$deny && $data['deny']) continue;
				$new_country[$data['region']][$data['zone']][$code] = $data['name'];
			}
		}
        $new_countries = self::filterCountry($new_country);
		return json_encode($new_countries);
	}

    public static function filterCountry($countries)
    {
        $new_countries = array();
        foreach($countries as $region=>$sub_region)
        {
            foreach($sub_region as $region_name => $country_val)
            {
                $regions = self::parseXml(AC::COUNTRY_LIST_CODE, false,$region_name);
                if(count($country_val) == count($regions[$region_name]))
                {
                    $new_countries[$region_name] = 'ALL';
                }
                else
                {
                    $new_countries[$region_name][$region_name] =  $country_val;
                }
            }
        
        }
        return $new_countries;
    }

	/**
	 * Change country_allow/deny_list format from  {"Asia":{"Asia":{"HK":"Hong Kong ","MO":"Macau "}}} to "HK,MO"
	 *
	 * @author vanni.fan@achievo.com
	 * @param string $str
	 * @return string 
	 */
	public static function json2country($str){
		if(strtoupper(substr($str,0,3))=='ALL' || !trim($str)) return strtoupper(trim($str));

		$countries = json_decode($str);
		if(empty($countries)) return '';

		$new_countries = array();
        $all_country_list = array();
		foreach($countries as $zones_code=>$zones){
            if('ALL' == $zones)
            {
                $all_country = self::getAllCountryByZone($zones_code);
                $all_country_list = array_merge($all_country_list,$all_country);
            }
            else{
                foreach($zones as $_countries){
                    foreach($_countries as $code=>$name){
                        $new_countries[$code] = $name;
                    }
                }
            }
		}
        $new_country = array_merge($all_country_list,array_keys($new_countries));
		return implode(',',$new_country);
	}

    public static function getAllCountryByZone($zone)
    {
        $region = self::parseXml(AC::COUNTRY_LIST_CODE, true,$zone);
        foreach($region[$zone] as $country_code => $country_val)
        {
            $country[] = $country_code;
        }
        return $country;
    }
}

function tmp_usort_country($a, $b){
	$aa = is_string($a) ? $a : $a[0];
	$bb = is_string($b) ? $b : $b[0];
	
	$r = array($aa, $bb);
	sort($r);
	if($r[0] != $aa){
		return 1;
	}else{
		return -1;
	}
}

?>
